<?php

// +----------------------------------------------------------------------
// | Author: pp <124910168@qq.com>
// +----------------------------------------------------------------------

namespace controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use think\Config;
use think\Env;
use think\paginator\driver\Bootstrap;
use service\SmsService;
use service\DataService;
use service\ToolsService;

/**
 * 前端基类
 */
class HomeBase extends Controller{

    protected $param;

    protected $themes;

    protected $template_dir;

    protected $method;

    protected $trueUrl;

    protected $d;//站点id

    protected $config;

    protected $windowEnv; // js 全局变量设置

    // 获取当前的模块，控制器和方法名
    protected $module = ''; // 页面module
    protected $controller = ''; // 页面controller
    protected $action = ''; // 页面action

    protected $menu; // 前端顶部导航

    protected $footerMenu; // 前端底部导航

    protected $newsTopMenu; // 前端新闻顶部导航

    protected $page;
    protected $cate;
    protected $domain; // 站点model
    protected $domainInfo; // 站点信息
    protected $temp; // 模板model
    protected $tempInfo; // 模板信息
    protected $tid; // 模板tid
    // protected $category; // 栏目
    protected $article; // 文章
    protected $area; // 地区
    protected $areaInfo; // 地区信息
    protected $aid; // 地区aid

    protected $databasepp;
    protected $databasefp;
    protected $databasepx;
    protected $databasefw;
    protected $categorypp;
    protected $categoryfp;
    protected $categorypx;
    protected $category;

    function __construct(Request $request = null)
    {        
        parent::__construct($request);
        // $this->config = Config::get('setting.home');
        // $this->param = $request->param();
        // $this->method = $request->method();
        // $this->trueUrl = trim($request->url(true));
        // halt($this->trueUrl);

        // 获取当前的模块，控制器和方法名
        $this->module = $request->module();
        $this->controller = $request->controller();
        $this->action = $request->action();

        //Model
        $this->domain = model('Domain');
        $this->temp = model('Temp');
        // $this->category = model('Category');

        $this->databasefw = db::connect(config('dbx.FW'));
        $this->databasepp = db::connect(config('dbx.PP'));
        $this->databasepx = db::connect(config('dbx.PX'));
        $this->databasefp = db::connect(config('dbx.FP'));

        //调用公共服务栏目表
        $this->categoryfw = $this->databasefw->name('category');
        //调用公共品牌栏目表
        $this->categorypp = $this->databasepp->name('category');
        //调用人才培训栏目表
        $this->categorypx = $this->databasepx->name('category');
        //调用电商扶贫栏目表
        $this->categoryfp = $this->databasefp->name('category');

        $this->article = model('Article');
        $this->area = model('Area');

        //Domain
        $sName = trim($_SERVER['SERVER_NAME']);
        // $sName = trim(request()->domain());
        $pDomain = input('domain');
        $domainName = $pDomain ? $pDomain : $sName;
        $defDomainInfo = $this->domain->getOneDarry(['domain' => $domainName]);//默认州or县站点
        // halt($defDomainInfo);
        if(!$defDomainInfo){
            $this->error("找不到站点");
        }elseif ($defDomainInfo['status'] == 1) {
            $this->error("站点已被禁用，请联系管理员");
        }

        if(input('d')){
            session('d', input('d'));
        }

        $this->d = session('d') ? session('d') : $defDomainInfo['id'];
        $this->domainInfo = $this->domain->getOneDarry(['uname|id' => $this->d]);
        // halt($this->domainInfo);
        // $aid = input('aid');
        // halt($aid);
        $this->aid = isset($this->domainInfo['zone_id']) ? $this->domainInfo['zone_id'] : 1;
        // $this->aid = isset($aid) ? $aid : (isset($this->domainInfo['zone_id']) ? $this->domainInfo['zone_id'] : 1);
        session('aid', $this->aid);
        // halt($this->aid);
        // halt(session('aid'));
        
        $areas = $this->area->order('area_id asc')->select();
        $this->aids = ToolsService::getArrSubIds($areas,$this->aid,'area_id','area_parent_id');//当前区域下地区Ids

        $this->tid = isset($this->domainInfo['temp_id']) ? $this->domainInfo['temp_id'] : 1;
        $this->tempInfo = $this->temp->getOneDarry(['id' => $this->tid]);
        if(!$this->tempInfo){
            $this->error("找不到模板");
        }elseif ($this->tempInfo['status'] == 1) {
            $this->error("模板已被禁用，请联系管理员");
        }
        $this->themes = $this->tempInfo['path'];
        // halt($this->themes);


        //mca定位兼容ajax

//         //mca定位兼容ajax

//         $aName = $this->action;
//         $ajaxArr = ['ajax','ajaxAsk','ajaxPost'];
//         if(in_array($aName, $ajaxArr)){
//             $aNameArr = ['act'=>input('act'),'sAction'=>input('sAction'),'action'=>input('action')];
//             $aNameArr = array_filter($aNameArr);
//             sort($aNameArr);
//             $aName = $aName.'/logic/'.$aNameArr[0];
//         }

//         $mca = $this->module.'/'.$this->controller.'/'.$aName; //定位动作

//         // TODO 初始化检查登录状态

//         // TODO 初始化地区选择数据
//         // 获取地区列表
//         $areaList = model('area')->getOpenAreaList();
//         $this->assign('areaList', $areaList);

//         $currentAreaId = 25;
//         if(session('current_area_id')) {
//             // 如果session中不存在默认地区id 则将默认地区设置为云南 25
//             $currentAreaId = session('current_area_id');
//         }
//         $currentAreaName = model('area')->getAreaNameById($currentAreaId);

//         $this->assign('currentAreaId', $currentAreaId); // 初始化默认地区为云南
//         $this->assign('currentAreaName', $currentAreaName);


//         // 获取友情链接
//         // 友情链接
//         // 友情链接
//         $fLinks = model('links')->getDatas(1); // 获取友情链接
//         $this->assign('fLinks', $fLinks);
//         $hLinks = model('links')->getDatas(2); // 获取合作单位链接
//         $this->assign('hLinks', $hLinks);


//         // TODO 获取前端菜单
//         // 顶部导航菜单
//         $this->makeMenuTree(1,$this->menu);
// //        $this->makePathMenu();

//         // TODO 获取前端底部菜单
//         $this->makeMenuTree(2, $this->footerMenu);
// //        $this->makePathMenu();

//         // TODO 获取前端新闻顶部导航
//         $this->makeMenuTree(5, $this->newsTopMenu);
//         $this->makePathMenu();



        // 如果在控制器中没有自定义主题 则使用下面的设置
        if(!$this->themes) {
            // 设置PC端模板
            $this->themes = 'state';

            // 设置手机模板
            // if($this->request->isMobile()){
            //    $this->redirect('/mobile');
            // }
//            if ($this->request->isMobile()) {
//
//                // 过滤不跳转手机端的页面
//                $filterArr = [
//                    'module' => [
//                        'cms'
//                    ],
//                    'mca' => [
////                        'home/Tools/test'
//                    ]
//                ];
//                if(!in_array($this->module, $filterArr['module']) && !in_array($mca, $filterArr['mca'])){
//                    //手机端模板
//                    $this->themes = 'mobile';
//                }
//            }
        }

        $this->theme(); //模板初始化
//        dump($this->menu);die;
        // $this->assign('menu',$this->menu);
        // $this->assign('footerMenu',$this->footerMenu);
        // $this->assign('newsTopMenu',$this->newsTopMenu);

        //判断是否是wap端
        // if(is_mobile()){
        //     $this->redirect('mobile/index/index');
        // }

    }

    /*模板相关*/
    protected function theme(){


        $this->windowEnv['domain'] = Env::get('web.host');

        $this->assign('windowEnv',json_encode($this->windowEnv));

        $this->assign('themes', $this->themes);
        $this->assign('d', $this->d);
        $this->assign('web_title', sysconf('web_title'));
        $this->assign('seo_title', sysconf('seo_title'));
        $this->assign('seo_keywords', sysconf('seo_keywords'));
        $this->assign('seo_description', sysconf('seo_description'));

    }

    protected function fetch($template = '', $vars = [], $replace = [], $config = [], $pathhandl = true)
    {
        if($template == '') {
            // 如果传入的模板为空则调用当前action方法
            $template = strtolower($this->request->action());
        }
        if ($pathhandl) {
            $this->template_dir = $this->themes."/".strtolower($this->request->module())."/".strtolower($this->request->controller())."/".$template;
        } else {
            //empty 控制器
            $this->template_dir = $this->themes."/".strtolower($this->request->module())."/".$template;
        }
        $config['view_path'] = Config::get("template.view_path") . $this->themes . "/";
        return parent::fetch($this->template_dir, $vars, $replace, $config); // TODO: Change the autogenerated stub
    }

    //任意数组打包分页
    //$data 需要输出的数组 mixed
    //$pageSize 每页数量 int
    //$list 分页数据 mixed
    //$p 分页 string
    public function pPage($data, $pageSize = 20){
            if(!$data)return [[],''];
            $curpage = input('page') ? input('page') : 1;//当前第x页，有效值为：1,2,3,4,5...
            $listRow = $pageSize;//每页10行记录
            $dataTo=array();
            $dataTo=array_chunk($data,$listRow);
            $showdata=array();
            if($dataTo){
                $showdata = $dataTo[$curpage-1];
            }
            else{
                $showdata=null;
            }
            $list = Bootstrap::make($showdata, $listRow, $curpage, count($data), false, [
                'var_page' => 'page',
                'path'     => request()->action(),//这里根据需要修改url
                'query'    => input(''),
                'fragment' => '',
            ]);
            $list->appends(input(''));
            $p = $list->render();
            return [$list, $p];
            // $this->assign('list', $list);
            // $this->assign('page', $list->render());
    }    

    //SEO_EXT title keywords description
    function seo_ext($arr){
        $seoTitle = sysconf('seo_title');
        $seoKey = sysconf('seo_keywords');
        $seoDesc = sysconf('seo_description');
        if($arr){
            if(is_array($arr)){
                $seoArr1 = array_merge($arr, [$seoTitle]);
                $seoArr2 = array_merge($arr, [$seoKey]);
                $seoArr3 = array_merge($arr, [$seoDesc]);
                $seoTitle = implode('|', $seoArr1);
                $seoKey = implode(',', $seoArr2);
                $seoDesc = implode(',', $seoArr3);
            }else{
                $seoTitle = $arr.'|'.$seoTitle;
                $seoKey = $arr.','.$seoKey;    
                $seoDesc = $arr.','.$seoDesc;                
            }
        }
        $this->assign('seo_title', $seoTitle);
        $this->assign('seo_keywords', $seoKey);
        $this->assign('seo_description', $seoDesc);
    }

    //获取栏目+内容数据
    protected function _getTopColumn($cid = 0, $limit = 5){
        $r = cate_auth_chunk($this->aid);
        $cMap = [
            'parentid' => $cid,
            'ismenu' => 1,
            // 'readgroup' => ['in',$r],
        ];
        // $topColumn = $this->category->getLists($cMap, 'sort', 'id,catname,image,module,readgroup', $limit);
        $topColumn = $this->category->getLists($cMap, 'sort', 'id,catname,image,module,readgroup', '');
        // halt($topColumn);

        foreach ($topColumn as $k => $v) {
            // if(!in_array($r, explode(',',$v['readgroup']))){
            $groupArr = explode(',',$v['readgroup']);
            if(!cate_mup($r,$groupArr)){
                unset($topColumn[$k]);
                continue;
            }
            if($v['module'] == 'page'){
                $mid = 'id';
                $m = $this->page;
            }else{
                $mid = 'catid';
                $m = $this->article;
            }
            $aMap = [
                "$mid" => $v['id'],
                // 'userid' => $this->uid,
                'aid' => $this->aid,
            ];
            $topColumn[$k]['sub'] = $m->getLists($aMap);
        }
        return $topColumn;
    }

    //地区三级联动
    public function _select_area(){
        // if(!input('pid'))return [];
        // return Db::name("FpArea")->where(['pid' => input('pid')])->select();
        return $this->area->getLists(['pid' => input('pid')]);
    }

    //session update
    public function _sessData(){
        $ret = 0;
        $city_id = input('city_id');
        if(!$city_id)return $ret;
        session('city_id', $city_id);
        session('aid', $city_id);
        return 1;
    }

    //get module obj
    protected function _getModelObj($cid){
        $ob = [];
        $cate = $this->category->getOneDarry(['id' => $cid], 'id,module');
        if($cate['module'] == 'page'){
            $mid = 'id';
            $m = $this->page;
        }else{
            $mid = 'catid';
            $m = $this->article;
        }
        $ob['m'] = $m;
        $ob['map'] = [
            "$mid" => $cate['id'],
            // 'userid' => $this->uid,
            'aid' => $this->aid,
        ];
        return $ob;
    }

    /**
     * 设置js全局变量
     * @param $data
     */
    public function setValueInEnv($data){
        foreach($data as $k => $v){
            $this->windowEnv[$k] = $v;
        }
        $this->assign('windowEnv',json_encode($this->windowEnv,JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK));
    }

    /**
     * ajax 返回
     * @param int $result
     * @param array $data
     * @param string $msg
     * @return mixed
     */
    protected function response($result = 0, $data = [], $msg = ''){
        return json(['result' => $result, 'data' => $data, 'msg' => $msg]);
    }

    protected function makeMenuTree($parent_id=0,&$parent_menu=[],$all=false){
        $db = Db::name("site_column")->alias('menu')->where('menu.pid',$parent_id);
        if(!$all){
            $db->where('status',1);
        }

        $menu = $db->order('sort asc')->select();
        foreach ($menu as $m){
            $parent_menu[$m['id']] = $m;
            $this->makeMenuTree($m['id'],$parent_menu[$m['id']]['sub'],$all);
        }
        return $menu;
    }

    private function makePathMenu(){
        $menu = Db::name("site_column")->where('pid','neq',0)->order('sort asc')->select();
        foreach ($menu as $m){
            $key = strval($m['url']);
            $this->menu_path[$key] = $m;
        }
        return $menu;
    }

    //根据地区aid获取站点信息树
    protected function getDomainTree($aid = 1){
        // $domainz = get_domain('zone_id', $aid);
        $domainz = [];
        $subpAreas = $this->area->getLists(['area_parent_id' => $aid], 'area_sort asc,area_id asc', 'area_id,area_name,area_parent_id','');
        // halt($subpAreas);
        foreach ($subpAreas as $k => $v) {
            $domainInfo = get_domain('zone_id', $v['area_id']);
            // halt($domainInfo);
            $domainz[$k] = $v;
            $domainz[$k]['id'] = $v['area_id'];
            $domainz[$k]['domain'] = '';
            $domainz[$k]['title'] = '';
            $domainz[$k]['contact'] = '';
            $domainz[$k]['tel'] = '';
            $domainz[$k]['desc'] = '';
            $domainz[$k]['zone_id'] = $v['area_id'];
            if(isset($domainInfo) && $domainInfo['is_deleted'] == '0'){
                $domainz[$k] = array_merge($v, $domainInfo);
            }
            // if($domainInfo){
            //     if($domainInfo['is_deleted'] == '1'){
            //         $domainz[$k] = $v;
            //     }else{
            //         $domainz[$k] = array_merge($v, $domainInfo);
            //     }
            // }else{
            //     $domainz[$k] = $v;
            // }
            // $domainz[$k]['domain_id'] = $domainInfo['id'];
            // $domainz[$k]['domain_title'] = $domainInfo['title'];
            // $domainz[$k]['domain_url'] = $domainInfo['domain'];
            // $domainz[$k]['desc'] = $domainInfo['desc'];
            // $domainz[$k]['content'] = $domainInfo['content'];
            // $domainz[$k] = array_merge($domainz[$k], $domainInfo);
            // array_push($domainz[$k], $domainInfo);
            $subIds = $this->area->getColumn(['area_parent_id' => $v['area_id']], 'area_id');
            $domainz[$k]['sub'] = $this->domain->getLists(['zone_id' => ['in', $subIds]], '', 'id,title,domain,zone_id,desc,content','');
        }
        // halt($domainz);
        return $domainz;
    }

//    public function _empty(){
//        echo __FUNCTION__;
//        return "the function not exits";
//    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
        Session::set('last_url',$this->request->url());
    }
}